import React, { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { getRole4UserAuth } from '@/services/system/role';
import { Spin, Transfer } from 'antd';
import { saveRole4UserAuth } from '@/services/system/role';

// 定义传参
interface RoleUserParams {
  roleId: string;
}

// 参数
interface roleUserData {
  userData: System.UserAuth4Role;
}

/**
 * 用户角色授权
 *
 * @author zhangby
 * @date 24/9/20 12:08 pm
 */
const RoleUser: React.FC<RoleUserParams> = (props, ref) => {
  const [loading, setLoading] = useState(false);
  const [roleUserData, setRoleUserData] = useState<roleUserData>({ userData: {} });

  // 设值
  const setData = (data: any) => {
    setRoleUserData({ ...roleUserData, ...data });
  };

  // 父类调用
  useImperativeHandle(ref, () => ({
    // changeVal 就是暴露给父组件的方法
    onSubmit: async () => {
      // 提交
      const data = await saveRole4UserAuth(props.roleId, roleUserData.userData.checked.join(','));
      return data;
    },
  }));

  // 初始化
  // @ts-ignore
  useEffect(() => {
    try {
      setLoading(true);
      getRole4UserAuth(props.roleId).then((res) => {
        if (res.code === '000') {
          setData({ userData: res.result });
          setLoading(false);
        }
      });
    } catch (e) {
      setLoading(false);
    }
  }, []);

  return (
    <>
      <h3 style={{ margin: '20px 0' }}>菜单授权</h3>
      <Spin spinning={loading}>
        <Transfer
          titles={['用户列表', '选中用户']}
          dataSource={roleUserData.userData.userList}
          targetKeys={roleUserData.userData.checked}
          showSearch
          listStyle={{
            width: 280,
            height: 450,
            marginTop: 10,
          }}
          render={(item) => (
            <span>
              {item.name}（ {item.loginName} ）
            </span>
          )}
          onChange={(targetKeys) =>
            setData({ userData: { ...roleUserData.userData, checked: targetKeys } })
          }
        />
      </Spin>
    </>
  );
};

// @ts-ignore
export default forwardRef(RoleUser);
